package leetCode;

import java.util.*;

public class t350 {
    public static void main(String[] args) {
        new Solutiont350().intersection(new int[]{1,2,2,1},new int[]{2,2});
    }
}
class Solutiont350 {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashMap<Integer, List<Integer>>num1HashMap=new HashMap<>();
        HashMap<Integer, List<Integer>>num2HashMap=new HashMap<>();

        for (int i=0;i<nums1.length;i++){
            List<Integer> orDefault = num1HashMap.getOrDefault(nums1[i], new ArrayList<>());
            orDefault.add(nums1[i]);
            num1HashMap.put(nums1[i],orDefault);
        }
        for (int i=0;i<nums2.length;i++){
            List<Integer> orDefault = num2HashMap.getOrDefault(nums2[i], new ArrayList<>());
            orDefault.add(nums2[i]);
            num2HashMap.put(nums2[i],orDefault);
        }
        Set<Integer> integers = num2HashMap.keySet();
        Iterator<Integer> iterator = integers.iterator();

        List<Integer> ret=new ArrayList<>();
        while (iterator.hasNext()){
            Integer next = iterator.next();
            if (num1HashMap.containsKey(next)){
                if (num1HashMap.get(next).size()<=num2HashMap.get(next).size()){
                    ret.addAll(num1HashMap.get(next));
                }else {
                    ret.addAll(num2HashMap.get(next));
                }
            }
        }
        int[] ints = ret.stream().mapToInt(i -> i).toArray();
        return ints;

    }
}
